$(document).ready(function() {
    $("a.fb-connect, li.fb-connect-li").live('click', function() {
        FB.login(function(response) {
            if (response.session) {
                if (response.perms) {
                    $.post("/fb_connect","", function(data) {
                        if (data.new_user) {
                            $.fn.colorbox({href: data.redirect_to, innerWidth: '800', overlayClose: false, escKey: false, arrowKey: false});
                        } else {
                            if (data.show_connect_confirmation) {
                                $.fn.colorbox({href: data.confirm_url + "?redirect_to=" + escape(data.redirect_to), innerWidth: '400', overlayClose: false, escKey: false, arrowKey: false});
                            } else {
								if (data.redirect_to) {
									window.location = data.redirect_to;
								} else {
									window.location.reload();
								}
                            }
                        }
                    });
                } else {
                    alert("Please grant the corresponding permissions to YouthSays to connect your Facebook account.");
                }
            } else {
                // user is not logged in
            }
        }, {perms:'email,user_birthday,user_hometown'});
        return false;
    });

    $("a.fb-connecta").click(function() {
       alert("clicked");
       return false;
    });

    $("a.require-login").click(function() {
        var url = $(this).attr("href");
        if (is_logged_in) {
            if ($(this).hasClass("lightbox-link")) {
                $.fn.colorbox({'href' : url, 'maxWidth' : 800, 'overlayClose' : false, 'escapeKey' : false});
                return false;
            } else if ($(this).hasClass("normal-link")) {
                return true;
            }
        } else {
            var redirect_to = $(this).attr("rel");
			var href = "/signup";
            if (redirect_to) {
				href += "?return_to=" + escape(redirect_to);
                //$.cookie("redirect_to",redirect_to,{path: '/',expires: 3});
            }
            $.fn.colorbox({'href' : href, 'overlayClose' : false, 'escapeKey' : false});
            return false;
        }
    });

    $("form.require-login").submit(function() {
        if (is_logged_in) {
            return true;
        } else {
            var return_to = window.location;
			var href = "/signup";
			href += "?return_to=" + escape(return_to);
			
            var dataString = $(this).serialize();
            $.cookie($(this).attr("id"),dataString);
            $.fn.colorbox({'href' : href, 'overlayClose' : false, 'escapeKey' : false});
            return false;
        }
    });
});